package com.wang.mvchain.outer.service.implay;

import java.io.IOException;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.HmacUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wang.mvchain.common.util.ConstatFinalUtil;
import com.wang.mvchain.common.util.HTTPUtil;
import com.wang.mvchain.outer.enums.TradeEnum;
import com.wang.mvchain.outer.service.ITradeService;

/**
 * 火币ProAPI工具
 * 
 * @author wangsh
 *
 */
public class HuobiTradeServiceImplay extends BaseTradeService implements ITradeService
{
	private String account_id = "243187" ; 
	
	/* 请求服务的serverUrl  */
	private String serverUrl = "http://api.huobi.co" ; 
	
	//登陆验证的信息,可从网站模板中查找
	private JSONObject authJSON;
	
	@Override
	public int findWebsiteId()
	{
		return 14;
	}
	
	/**
	 * 得到UTC时间，类型为字符串，格式为"yyyy-MM-dd HH:mm"<br />
	 * 如果获取失败，返回null
	 * 
	 * @return
	 */
	public static String getUTCTimeStr() {
		// 1、取得本地时间：
		Calendar cal = Calendar.getInstance();
		// 2、取得时间偏移量：
		int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
		// 3、取得夏令时差：
		int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
		// 4、从本地时间里扣除这些差量，即可以取得UTC时间：
		cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
		return format.format(cal.getTime());
	}
	
	/**
	 * 获取签名方式
	 * 
	 * @return
	 */
	private String authSign(Map<String, String> headerMap,Map<String, String> paramsMap)
	{
		try
		{
			String serverUrl = headerMap.get("serverUrl") ;
			//String serverUrl = "api.huobi.pro" ; 
			String preUrl = headerMap.get("method") + "\n" + serverUrl + "\n" + headerMap.get("fileUrl") + "\n" ; 
			
			/* 请求头中的参数都要经过URL:加密 */
			paramsMap.put("SignatureMethod", "HmacSHA256");
			paramsMap.put("SignatureVersion", "2");
			
			Calendar calendar = Calendar.getInstance() ; 
			calendar.add(Calendar.HOUR_OF_DAY, -8);
			//paramsMap.put("Timestamp", dateUtil.format(calendar.getTime(), "yyyy-MM-dd'T'HH:mm:ss"));
			paramsMap.put("Timestamp", getUTCTimeStr());
			
			StringBuffer sb = new StringBuffer();
			Map<String, String> signMap = new TreeMap<String, String>();
			signMap.putAll(paramsMap);
			for (Iterator iterator = signMap.entrySet().iterator(); iterator
					.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				String key = me.getKey() + "";
				String value = me.getValue() + "";
				if ("requestURL".equalsIgnoreCase(key))
				{
					continue;
				}
				
				String valEncode = URLEncoder.encode(value, "UTF-8") ; 
				if(!valEncode.equalsIgnoreCase(value))
				{
					value = valEncode.toUpperCase() ; 
					paramsMap.put(key, value);
				}
				sb.append(key + "=" + value + "&");
			}
			
			if (sb.toString().lastIndexOf("&") != -1)
			{
				sb.delete(sb.lastIndexOf("&"), sb.length());
			}
			
			String str = sb.toString() ; 
			/* 将前置字符串加上 */
			str = preUrl + str ; 
			String sign = "" ;
			/* 使用hmac256加密 */
			byte[] b = HmacUtils.hmacSha256(authJSON.get("secret_key") + "", str);
			sign =  Base64.encodeBase64String(b);
			return URLEncoder.encode(sign,"UTF-8") ; 
		} catch (Exception e)
		{
		}
		return "" ; 
	}

	/**
	 * 获取用户基本信息
	 * var res = {
			"available_btc_display" : "0.0000",
			"available_cny_display" : "0.26",
			"available_ltc_display" : "0.0000",
			"frozen_btc_display" : "0.0000",
			"frozen_cny_display" : "0.00",
			"frozen_ltc_display" : "0.0000",
			"loan_btc_display" : "0.0000",
			"loan_cny_display" : "0.00",
			"loan_ltc_display" : "0.0000",
			"net_asset" : "0.26",
			"total" : "0.26"
		}
	 * @return
	 */
	public JSONObject getUserInfo(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		
		/* 文件URL */
		String fileUrl = "/v1/account/accounts/"+ account_id +"/balance" ; 
		paramsMap.put("requestURL", serverUrl + fileUrl);
		
		HTTPUtil httpUtil = new HTTPUtil();
		/* 请求头 */
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("method", "GET");
		headerMap.put("serverUrl", serverUrl.substring(serverUrl.indexOf("http://") + "http://".length()));
		headerMap.put("fileUrl", fileUrl);
		
		paramsMap.put("AccessKeyId", authJSON.get("access_key") + "");
		/* 账户id */
		paramsMap.put("account-id", account_id);
		/* 添加参数 */
		String sign = authSign(headerMap,paramsMap);
		paramsMap.put("Signature", sign);
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ;
		try
		{
			result = httpUtil.methodGet(paramsMap);
			responseJSON = (JSONObject) JSON.parse(result);
			
			if(responseJSON == null)
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6"));
				return responseJSON;
			}
			
			//按照接口的格式拼装json
			JSONObject dataJSON = new JSONObject();
			JSONObject balanceJSON = new JSONObject();
			JSONObject fundJSON = new JSONObject();
			
			if("ok".equalsIgnoreCase(responseJSON.getString("status")))
			{
				/* 取得账户列表 */
				JSONObject dataResJSON = (JSONObject) responseJSON.get("data");
				JSONArray listArr = (JSONArray) dataResJSON.get("list");
				for(Iterator iter = listArr.iterator() ; iter.hasNext();)
				{
					JSONObject listTemp = (JSONObject) iter.next() ; 
					if("trade".equalsIgnoreCase(listTemp.getString("type")))
					{
						/* 交易余额 */
						balanceJSON.put(listTemp.get("currency") + "", listTemp.get("balance") + "");
					}else if("frozen".equalsIgnoreCase(listTemp.getString("type")))
					{
						/* 冻结余额 */
						fundJSON.put(listTemp.get("currency") + "", listTemp.get("balance") + "");
					}
				}
				dataJSON.put("balance", balanceJSON);
				dataJSON.put("fund", fundJSON);
				
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6"));
			}
			//ConstatFinalUtil.OUTER_LOG.info(this.findid() + "--获取用户信息--" + responseJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取用户信息失败."
					+ paramsMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}
	
	private JSONObject getUserId(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		/* 文件URL */
		String fileUrl = "/v1/account/accounts" ; 
		paramsMap.put("requestURL", serverUrl + fileUrl);
		
		HTTPUtil httpUtil = new HTTPUtil();
		/* 请求头 */
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("method", "GET");
		headerMap.put("serverUrl", serverUrl.substring(serverUrl.indexOf("http://") + "http://".length()));
		headerMap.put("fileUrl", fileUrl);
		
		paramsMap.put("AccessKeyId", authJSON.get("access_key") + "");
		/* 添加参数 */
		String sign = authSign(headerMap,paramsMap);
		paramsMap.put("Signature", sign);
		
		String result = "" ;
		try
		{
			result = httpUtil.methodGet(paramsMap);
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--获取账户列表--" + result + "---paramsMap:" + paramsMap);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取用户信息失败."
					+ paramsMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 下单交易
	 * 
	 * @return
	 */
	public JSONObject trade(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.trade(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		resultJSON = new JSONObject() ;
		
		HTTPUtil httpUtil = new HTTPUtil();
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("AccessKeyId", authJSON.get("access_key") + "");
		
		/* 文件URL */
		String fileUrl = "/v1/order/orders/place" ; 
		
		/* 请求头 */
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("method", "POST");
		headerMap.put("serverUrl", serverUrl.substring(serverUrl.indexOf("http://") + "http://".length()));
		headerMap.put("fileUrl", fileUrl);
		
		String sign = authSign(headerMap,requestMap);
		requestMap.put("Signature", sign);
		
		JSONObject reqJSON = new JSONObject();
		/* 要加上参数的 */
		reqJSON.put("account-id", this.account_id + "");
		//转换货币类型
		String moneytype = this.convertMoneyType(paramsMap.get("moneytype"));
		reqJSON.put("symbol", moneytype);
		
		// 买还是卖.0:买,1:卖
		if (paramsMap.get("type").equalsIgnoreCase(TradeEnum.TRADE_TYPE_BUY.getValue() + ""))
		{
			reqJSON.put("type", "buy-limit");
		} else if (paramsMap.get("type").equalsIgnoreCase(TradeEnum.TRADE_TYPE_SELL.getValue() + ""))
		{
			reqJSON.put("type", "sell-limit");
		}
		
		/* 处理小数点以后的位数 */
		double price = doubleOperUtil.round(Double.valueOf(paramsMap.get("price") + ""), 2, RoundingMode.DOWN.ordinal());
		
		reqJSON.put("price", price + "");
		reqJSON.put("amount", paramsMap.get("amount"));
		reqJSON.put("source", "api");
		
		Map<String, String> resultMap = new TreeMap<String, String>();
		String requestURL = serverUrl + fileUrl + "?";
		for (Iterator iterator = requestMap.entrySet().iterator(); iterator.hasNext();)
		{
			Entry me = (Entry) iterator.next();
			String key = me.getKey() + "" ;
			String value = me.getValue() + ""; 
			requestURL += key + "=" + value + "&"; 
		}
		/* 边完成的一个url都要做好处理 */
		requestURL = requestURL.substring(0, requestURL.length() - 1);
		resultMap.put("requestURL", requestURL);
		/* 设置MIME类型 */
		resultMap.put("Content-Type", "application/json");
		String result = null ;
		try
		{
			result = httpUtil.methodPost(resultMap,reqJSON.toString());
			JSONObject responseJSON = (JSONObject) JSON.parse(result);
			if(responseJSON == null)
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6"));
				return responseJSON;
			}
			
			if("ok".equalsIgnoreCase(responseJSON.get("status") + ""))
			{
				JSONObject dataJSON = new JSONObject();
				dataJSON.put("order_id", responseJSON.get("data"));
				
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.get("msg"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--下单交易返回--原始信息:" + result
				+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "下单交易失败."
					+ requestMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 撤销订单
	 * 
	 * var res = {
			"code" : 26,
			"msg" : "该委托不存在",
			"result" : "fail",
			"time" : 1417096047
		}
	 * @return
	 */
	public JSONObject cancelOrder(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.cancelOrder(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		resultJSON = new JSONObject() ;
		
		HTTPUtil httpUtil = new HTTPUtil();
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("order_id", paramsMap.get("order_id"));
		String fileUrl = "/v1/order/orders/"+ requestMap.get("order_id") +"/submitcancel" ; 
		requestMap.put("requestURL", serverUrl + fileUrl);
		requestMap.put("AccessKeyId", authJSON.get("access_key") + "");
		
		requestMap.remove("order_id");
		
		/* 请求头 */
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("method", "POST");
		headerMap.put("serverUrl", serverUrl.substring(serverUrl.indexOf("http://") + "http://".length()));
		headerMap.put("fileUrl", fileUrl);
		
		String sign = authSign(headerMap ,requestMap);
		requestMap.put("Signature", sign);

		JSONObject responseJSON = new JSONObject();
		String result = null ;
		try
		{
			result = httpUtil.methodPost(Collections.emptyMap(),requestMap);
			responseJSON = (JSONObject) JSON.parse(result);
			
			if(responseJSON == null)
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6"));
				return responseJSON;
			}
			
			if("ok".equalsIgnoreCase(responseJSON.get("status") + ""))
			{
				JSONObject dataJSON = new JSONObject();
				dataJSON.put("order_id", responseJSON.get("data"));
				
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.get("msg"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--取消订单息返回.--原始信息:" + result
				+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "撤销订单失败."
					+ paramsMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 获取用户挂单
	 * 
	 * @param args
	 */
	public JSONObject getOrders(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.getOrders(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		resultJSON = new JSONObject() ;
		
		String fileUrl = "/v1/order/orders" ; 
		HTTPUtil httpUtil = new HTTPUtil();
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("requestURL", serverUrl + fileUrl);
		requestMap.put("AccessKeyId", authJSON.get("access_key") + "");
		
		//转换货币类型
		String moneytype = this.convertMoneyType(paramsMap.get("moneytype"));
		requestMap.put("symbol", moneytype);
		requestMap.put("states", "submitted");
		
		/* 请求头 */
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("method", "GET");
		headerMap.put("serverUrl", serverUrl.substring(serverUrl.indexOf("http://") + "http://".length()));
		headerMap.put("fileUrl", fileUrl);

		String sign = authSign(headerMap , requestMap);
		requestMap.put("Signature", sign);
		String result = null ;
		try
		{
			result = httpUtil.methodGet(requestMap);
			JSONObject responseJSON = (JSONObject) JSON.parse(result);
			
			//按照接口的格式拼装json
			JSONObject dataJSON = new JSONObject();
			if("ok".equalsIgnoreCase(responseJSON.getString("status")))
			{
				JSONArray responseArr = responseJSON.getJSONArray("data");
				
				JSONArray ordersResArr = new JSONArray();
				for (Iterator iterator = responseArr.iterator(); iterator
						.hasNext();)
				{
					JSONObject ordersTemp = (JSONObject) iterator.next();
					/* 将交易网站中的订单
					 * 换成系统中需要的订单 */
					JSONObject ordersResJSON = convertOrders(moneytype, ordersTemp);
					
					ordersResArr.add(ordersResJSON);
				}
				
				dataJSON.put("ordersList", ordersResArr);
				
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";错误信息:" + responseJSON.getString("err-msg"));
			}
			
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--获取用户挂单--原始信息:" + result
					+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取用户挂单失败."
					+ paramsMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}
	
	/**
	 * 将交易网站中的订单换成系统订单
	 * @param moneytype	币种类型
	 * @param ordersTemp	交易网站中的订单对象
	 * @return
	 */
	public JSONObject convertOrders(String moneytype, JSONObject ordersTemp)
	{
		JSONObject ordersResJSON = new JSONObject();
		ordersResJSON.put("order_id", ordersTemp.get("id") + "");
		ordersResJSON.put("price", ordersTemp.get("price") + "");
		ordersResJSON.put("amount", ordersTemp.get("amount") + "");
		ordersResJSON.put("deal_amount", ordersTemp.get("field-amount") + "");
		//处理下单时间
		Date createDate = new Date(Long.valueOf(ordersTemp.get("created-at") + ""));
		ordersResJSON.put("create_date", this.dateUtil.formatDateTime(createDate));
		ordersResJSON.put("symbol", moneytype);
		String type = ordersTemp.get("type") + "";
		/* submit-cancel：已提交撤单申请 ,buy-market：市价买, sell-market：市价卖, buy-limit：限价买, sell-limit：限价卖 */
		if(type.indexOf("buy") != -1)
		{
			type = TradeEnum.TRADE_TYPE_BUY.getValue() + "" ; 
		}else if(type.indexOf("sell") != -1)
		{
			type = TradeEnum.TRADE_TYPE_SELL.getValue() + "" ; 
		}
		ordersResJSON.put("type", type + "");
		
		/* 
		 * pre-submitted 准备提交, 
		 * submitting , 
		 * submitted 已提交, 
		 * partial-filled 部分成交, 
		 * partial-canceled 部分成交撤销, 
		 * filled 完全成交, 
		 * canceled 已撤销
		 *  */
		String status = ordersTemp.get("state") + "" ; 
		if("canceled".equalsIgnoreCase(status))
		{
			status = TradeEnum.TRADE_STATUS_CANCEL.getValue() + "" ; 
		}else if("submitted".equalsIgnoreCase(status))
		{
			status = TradeEnum.TRADE_STATUS_DEAL_NO.getValue() + "" ; 
		}else if("partial-filled".equalsIgnoreCase(status)
				|| "partial-canceled".equalsIgnoreCase(status))
		{
			status = TradeEnum.TRADE_STATUS_DEAL_PART.getValue() + "" ; 
		}else if("filled".equalsIgnoreCase(status))
		{
			status = TradeEnum.TRADE_STATUS_DEALED.getValue() + "" ; 
		}
		ordersResJSON.put("status", status);
		return ordersResJSON;
	}

	/**
	 * 行情API
	 */
	public JSONObject queryTicker(Map<String, String> paramsMap)
	{

		HTTPUtil httpUtil = new HTTPUtil();
		String symbol = paramsMap.get("symbol");
		if ("ltc_cny".equalsIgnoreCase(symbol))
		{
			paramsMap.put("requestURL",
					"https://www.okcoin.com/api/ticker.do?symbol=ltc_cny");
		} else
		{
			paramsMap.put("requestURL", "https://www.okcoin.com/api/ticker.do");
		}

		paramsMap.remove("symbol");

		JSONObject resultJSON = new JSONObject();
		try
		{
			String result = httpUtil.methodGet(paramsMap);
			resultJSON = (JSONObject) JSON.parse(result);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "行情API失败."
					+ paramsMap, e);
		}
		return resultJSON;
	}

	/**
	 * depth(市场深度)
	 */
	public JSONObject queryDepth(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		
		HTTPUtil httpUtil = new HTTPUtil();
		Map<String, String> requestMap = new HashMap<String, String>();
		String moneytype = this.convertMoneyType(paramsMap.get("moneytype") + "");
		requestMap.put("requestURL", serverUrl + "/market/depth?symbol="+ moneytype + "&type=step0");

		JSONObject responseJSON = new JSONObject();
		String result = null ;
		try
		{
			result = httpUtil.methodGet(requestMap);
			responseJSON = (JSONObject) JSON.parse(result);

			// 拼装符合条件的json数据
			JSONObject dataJSON = new JSONObject();
			
			JSONObject tickJSON = responseJSON.getJSONObject("tick");
			int count = 0;
			// 按照规则排序的容器
			Map<Double, JSONObject> asksMap = new TreeMap<Double, JSONObject>();
			JSONArray asksResArr = new JSONArray();
			JSONArray asksArr = (JSONArray) tickJSON.get("asks");
			for (Iterator iterator = asksArr.iterator(); iterator.hasNext();)
			{
				JSONArray asksTempArr = (JSONArray) iterator.next();
				JSONObject askJSON = new JSONObject();
				askJSON.put("count", "1");
				askJSON.put("vol", asksTempArr.get(1) + "");
				askJSON.put("rate", asksTempArr.get(0) + "");

				asksMap.put(Double.valueOf(askJSON.get("rate") + ""), askJSON);
			}

			for (Iterator iterator = asksMap.entrySet().iterator(); iterator
					.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				double key = (Double) me.getKey();

				if (count >= ConstatFinalUtil.PAGE_BATCH_SIZE)
				{
					break;
				}

				JSONObject asksTemp = (JSONObject) me.getValue();

				asksResArr.add(asksTemp);
				count++;
			}

			dataJSON.put("asks", asksResArr);

			// 按照规则排序的容器
			count = 0;
			Map<Double, JSONObject> bidsMap = new TreeMap<Double, JSONObject>(
					new Comparator<Double>()
					{
						@Override
						public int compare(Double o1, Double o2)
						{
							return o2.compareTo(o1);
						}
					});
			JSONArray bidsResArr = new JSONArray();
			JSONArray bidsArr = (JSONArray) tickJSON.get("bids");
			for (Iterator iterator = bidsArr.iterator(); iterator.hasNext();)
			{
				JSONArray bidsTempArr = (JSONArray) iterator.next();
				JSONObject bidsJSON = new JSONObject();
				bidsJSON.put("count", "1");
				bidsJSON.put("vol", bidsTempArr.get(1) + "");
				bidsJSON.put("rate", bidsTempArr.get(0) + "");

				bidsMap.put(Double.valueOf(bidsJSON.get("rate") + ""), bidsJSON);
			}

			for (Iterator iterator = bidsMap.entrySet().iterator(); iterator
					.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				double key = (Double) me.getKey();

				if (count >= ConstatFinalUtil.PAGE_BATCH_SIZE)
				{
					break;
				}

				JSONObject bidsTemp = (JSONObject) me.getValue();

				bidsResArr.add(bidsTemp);
				count++;
			}
			dataJSON.put("bids", bidsResArr);
			
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			resultJSON.put("data", dataJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "depth(市场深度)失败."
					+ paramsMap, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * trades的格式,历史交易记录
	 */
	public JSONArray queryHistoryTrades(String symbol,
			Map<String, String> paramsMap)
	{

		HTTPUtil httpUtil = new HTTPUtil();

		if ("ltc_cny".equalsIgnoreCase(symbol))
		{
			paramsMap.put("requestURL",
					" https://www.okcoin.com/api/trades.do?symbol=ltc_cny");
		} else
		{
			paramsMap.put("requestURL",
					" https://www.okcoin.com/api/trades.do?");
		}
		JSONArray resultJSON = new JSONArray();
		try
		{
			String result = httpUtil.methodGet(paramsMap);
			resultJSON = (JSONArray) JSON.parse(result);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "历史交易记录失败."
					+ paramsMap, e);
		}
		return resultJSON;
	}

	/**
	 * 获取所有的行情
	 * 
	 * @return
	 */
	public JSONObject getTrade()
	{
		JSONObject resultJSON = new JSONObject();
		String hlUserURL = "http://www.okcoin.com/";
		try
		{
			// 请求服务
			Connection conn = Jsoup.connect(hlUserURL);
			conn.timeout(ConstatFinalUtil.REQ_CONNECT_TIMEOUT);

			conn.header(
					"Cookie",
					"abtest=\"16,34\\|18,41\\|22,60\\|14,29\\|15,33\"; userParamsCookie=trace=g1081; aburl=1; cy=160; __utma=1.543273261.1351234587.1351234587.1351234587.1; __utmz=1.1351234587.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _hc.v=\"\"22a8bf0b-7caf-468f-ac01-88534d000d02.1351216735\"\"; cye=zhengzhou; is=743412785865");
			conn.header(
					"User-Agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)");

			Document docu = conn.get();

			/* 买入成效价 */
			JSONArray mairuArr = new JSONArray();
			Elements mairuTrades = docu
					.getElementsByAttributeValue("class", "transaction").get(0)
					.child(1).children();
			for (Iterator iterator = mairuTrades.iterator(); iterator.hasNext();)
			{
				Element eleTemp = (Element) iterator.next();
				Elements tdsTemp = eleTemp.children();
				JSONObject mairuTempJSON = new JSONObject();
				// 1买入
				mairuTempJSON.put("type", tdsTemp.get(0).text());
				mairuTempJSON.put("price", tdsTemp.get(1).text());
				mairuTempJSON.put("num", tdsTemp.get(2).text());
				mairuArr.add(mairuTempJSON);
			}
			resultJSON.put("mairu", mairuArr);

			/* 买出成效价 */
			JSONArray maichuArr = new JSONArray();
			Elements maichuTrades = docu
					.getElementsByAttributeValue("class", "transaction").get(1)
					.child(1).children();
			for (Iterator iterator = maichuTrades.iterator(); iterator
					.hasNext();)
			{
				Element eleTemp = (Element) iterator.next();
				Elements tdsTemp = eleTemp.children();
				JSONObject maichuTempJSON = new JSONObject();
				// 1买入
				maichuTempJSON.put("type", tdsTemp.get(0).text());
				maichuTempJSON.put("price", tdsTemp.get(1).text());
				maichuTempJSON.put("num", tdsTemp.get(2).text());
				maichuArr.add(maichuTempJSON);
			}
			resultJSON.put("maichu", maichuArr);

		} catch (IOException e)
		{
			ConstatFinalUtil.OUTER_LOG.error("获取OKcoin的行情失败了", e);
		}
		return resultJSON;
	}

	public void setAuthJSON(JSONObject authJSON)
	{
		this.authJSON = authJSON;
	}

	@Override
	public String convertMoneyType(String moneytype)
	{
		return moneytype.replaceAll("_", "") ; 
	}

	@Override
	public String toString()
	{
		return "HuobiTradeServiceImplay [findid()=" + findWebsiteId() + "]";
	}

	@Override
	public JSONObject getOrdersSingle(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.getOrdersSingle(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		resultJSON = new JSONObject() ;
		
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("order_id", paramsMap.get("order_id"));
		
		String fileUrl = "/v1/order/orders/" + requestMap.get("order_id") ; 
		HTTPUtil httpUtil = new HTTPUtil();
		requestMap.put("requestURL", serverUrl + fileUrl);
		requestMap.put("AccessKeyId", authJSON.get("access_key") + "");
		
		/* 请求头 */
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("method", "GET");
		headerMap.put("serverUrl", serverUrl.substring(serverUrl.indexOf("http://") + "http://".length()));
		headerMap.put("fileUrl", fileUrl);
		
		String sign = authSign(headerMap,requestMap);
		requestMap.put("Signature", sign);
		String result = null ;
		try
		{
			result = httpUtil.methodGet(requestMap);
			JSONObject responseJSON = (JSONObject) JSON.parse(result);
			if(responseJSON == null)
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6"));
				return responseJSON;
			}
			
			JSONObject dataJSON = new JSONObject() ; 
			//按照接口的格式拼装json
			if("ok".equalsIgnoreCase(responseJSON.getString("status")))
			{
				JSONObject ordersTempJSON = (JSONObject) responseJSON.get("data");
				ordersTempJSON = this.convertOrders("", ordersTempJSON);
				
				dataJSON.put("orders", ordersTempJSON);
				
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--获取订单详情--原始信息:" + result
				+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取订单详情失败."
					+ paramsMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	@Override
	public String parseMoneyType(String moneytype)
	{
		return moneytype.replaceAll("-", "_").toLowerCase() ; 
	}

	@Override
	public String findWebSiteName()
	{
		return "huobi";
	}
	
	@Override
	public JSONObject findAllTransPair(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject() ;
		
		Map<String, String> requestMap = new HashMap<String, String>();
		
		String fileUrl = "/v1/common/symbols" ; 
		HTTPUtil httpUtil = new HTTPUtil();
		requestMap.put("requestURL", serverUrl + fileUrl);
		String result = null ;
		try
		{
			result = httpUtil.methodGet(requestMap);
			//ConstatFinalUtil.SYS_LOG.info("===" + result);
			JSONObject responseJSON = (JSONObject) JSON.parse(result);
			
			JSONObject dataJSON = new JSONObject() ; 
			//按照接口的格式拼装json
			if("ok".equalsIgnoreCase(responseJSON.getString("status")))
			{
				JSONArray dataResArr = (JSONArray) responseJSON.get("data");
				for (Iterator iterator = dataResArr.iterator(); iterator.hasNext();)
				{
					JSONObject resTempJSON = (JSONObject) iterator.next();
					
					/*
					 *  //交易货币币种,小写;
				        "base_currency":"BTC",
				        //币对名称,小写;
				        "instrument_id":"BTC-USDT",
				        //最小交易数量
				        "min_size":"0.001",
				        //计价货币币种,小写;
				        "quote_currency":"USDT",
				        //交易货币数量精度
				        "size_increment":"0.00000001",
				        //交易价格精度
				        "tick_size":"0.1"
					 * */
					JSONObject pairJSON = new JSONObject();
					String baseCurrency = resTempJSON.getString("base-currency").toLowerCase();
					String quoteCurrency = resTempJSON.getString("quote-currency").toLowerCase();
					String moneyType = baseCurrency + "_" + quoteCurrency ; 
					if(!quoteCurrency.toLowerCase().equals("usdt"))
					{
						continue ; 
					}
					
					pairJSON.put("name", moneyType);
					pairJSON.put("min_size", resTempJSON.get("min-order-amt") + "");
					pairJSON.put("base_currency", baseCurrency);
					pairJSON.put("quote_currency", quoteCurrency);
					pairJSON.put("size_increment", resTempJSON.get("amount-precision")+ "");
					pairJSON.put("tick_size", resTempJSON.get("price-precision")+ "");
					/* 存储到结果中 */
					dataJSON.put(pairJSON.get("name") + "", pairJSON);
				}
				
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取订单详情失败."
					+ paramsMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}
}
